package dao;

import java.sql.SQLException;

import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import common.Constants;

import domain.User;
import domain.UserRelation;

public class UserRelationImpl extends HibernateDaoSupport implements UserRelationDao {
	
	@Override
	public void addUserRelation(Integer fuid, User user) {
		UserRelation relation = new UserRelation(user);
		relation.setFuid(fuid);
		getHibernateTemplate().save(relation);
	}

	@Override
	public void deleteUserRelation(final Integer fuid, final Integer uid) {
		getHibernateTemplate().execute(new HibernateCallback() {
			@Override
			public UserRelation doInHibernate(Session session) throws HibernateException, SQLException {
				if (session != null && session.isOpen()) {
					String sql =
						new StringBuilder().append("DELETE FROM ").append(Constants.getDefaultSchema())
							.append(".t_user_relation ").append(" WHERE ").append(" t_r_fk_uid=:fuid ").append(" AND ")
							.append(" t_r_uid=:uid ").toString();
					SQLQuery query = session.createSQLQuery(sql);
					query.setInteger("fuid", fuid);
					query.setInteger("uid", uid);
					query.executeUpdate();
				}
				return null;
			}
		});
	}

}
